package db

import (
	"qkcoupon/models"
	"reflect"

	"encoding/json"

	"time"

	"doubimeizhi.com/utility"
	log "github.com/cihub/seelog"
)

// CheckExchangeCodeAddable 检测优惠码可用性，如果存在可用优惠码，
// 则检验其结束时间是否在新优惠码的开始时间之前，如冲突，阻止创建优惠码
func CheckExchangeCodeAddable(text string, tick int64) (bool, error) {
	sql := "SELECT exchange_id FROM exchange_info WHERE exchange_text=? AND end_tick>? AND available=true"
	info, err := qingkeMysqlHelper.Query(sql, text, tick)
	if err != nil {
		log.Warn(err.Error())
		return false, err
	}
	if len(info) < 1 {
		return false, nil
	}
	return true, nil
}

// CreateExchangeInfo 创建优惠码信息
func CreateExchangeInfo(info *models.PSQkCouponExchangeInfo) (string, error) {
	sql := "INSERT INTO exchange_info(exchange_id,exchange_text,available,bid,new_user,user_limit,coupon_count,coupon_limit,start_tick,end_tick,insert_tick,update_tick) VALUES(?,?,?,?,?,?,?,?,?,?,UNIX_TIMESTAMP(),UNIX_TIMESTAMP())"
	exchangeID := utility.GenerateUUIDToken()
	_, err := qingkeMysqlHelper.Insert(sql, exchangeID, info.Text, true, info.Bid, info.NewUserOnly, info.UserLimit, 0, info.CouponLimit, info.StartTick, info.EndTick)
	if err != nil {
		return "", err
	}
	return exchangeID, nil
}

// CreateExchangeRules 创建优惠码生成规则
func CreateExchangeRules(exchangeID string, rules *models.PSQkCouponExchangeRuleList) error {
	sql := "INSERT INTO exchange_rule(exchange_id,rule) VALUES(?,?)"
	ruleJSON, err := json.Marshal(rules)
	if err != nil {
		return err
	}
	_, err2 := qingkeMysqlHelper.Insert(sql, exchangeID, ruleJSON)
	if err2 != nil {
		return err2
	}
	return nil
}

// GetExchangeCode 获取优惠码信息
func GetExchangeCode(text string) (*models.PSQkCouponExchangeStatus, bool, error) {
	status := &models.PSQkCouponExchangeStatus{}
	isExist := false
	sql := "SELECT exchange_id,new_user,user_limit,coupon_count,coupon_limit FROM exchange_info WHERE exchange_text=? AND start_tick<? AND end_tick>? AND available=true ORDER BY end_tick DESC LIMIT 1"
	now := time.Now().Unix()
	info, err := qingkeMysqlHelper.Query(sql, text, now, now)
	if err != nil {
		log.Warn(err.Error())
		return status, isExist, err
	}
	if len(info) <= 0 {
		return status, isExist, nil
	}
	row := info[0]
	utility.SetTypeValue(row["exchange_id"], reflect.ValueOf(&status.ExchangeID).Elem())
	utility.SetTypeValue(row["new_user"], reflect.ValueOf(&status.NewUserOnly).Elem())
	utility.SetTypeValue(row["user_limit"], reflect.ValueOf(&status.UserLimit).Elem())
	utility.SetTypeValue(row["coupon_count"], reflect.ValueOf(&status.CouponCount).Elem())
	utility.SetTypeValue(row["coupon_limit"], reflect.ValueOf(&status.CouponLimit).Elem())
	isExist = true
	return status, isExist, nil
}

// CheckUserExchangeCount 检测用户是否到达领取该优惠码的次数上限，如未达到，返回true
func CheckUserExchangeCount(exchangeID string, uid string, limit int32) bool {
	// 因为用户对应的领取记录有可能不存在，所以查找不符合规定的记录，不存在即合规
	sql := "SELECT receiver FROM exchange_count WHERE exchange_id=? AND receiver=? AND exchange_count>=?"
	info, err := qingkeMysqlHelper.Query(sql, exchangeID, uid, limit)
	if err != nil {
		log.Warn(err.Error())
		return false
	}
	if len(info) > 0 {
		return false
	}
	return true
}

// GrabExchangeWithLimit 在有总数限制的情况下抢优惠码
func GrabExchangeWithLimit(exchangeID string) (bool, error) {
	sql := "UPDATE exchange_info SET coupon_count=coupon_count+1 WHERE exchange_id=? AND coupon_count<coupon_limit"
	count, err := qingkeMysqlHelper.Exec(sql, exchangeID)
	if err != nil {
		log.Warn(err.Error())
		return false, err
	}
	if count <= 0 {
		return false, nil
	}
	return true, nil
}

// GrabExchangeWithoutLimit 在没有有总数限制的情况下抢优惠码
func GrabExchangeWithoutLimit(exchangeID string) error {
	sql := "UPDATE exchange_info SET coupon_count=coupon_count+1 WHERE exchange_id=?"
	_, err := qingkeMysqlHelper.Exec(sql, exchangeID)
	if err != nil {
		log.Warn(err.Error())
		return err
	}
	return nil
}

// RecordUserExchange 记录用户领取优惠码的次数
func RecordUserExchange(exchangeID string, uid string) error {
	sql := "INSERT INTO exchange_count(exchange_id,receiver,exchange_count) VALUES(?,?,1) ON DUPLICATE KEY UPDATE exchange_count=exchange_count+1"
	_, err := qingkeMysqlHelper.Exec(sql, exchangeID, uid)
	if err != nil {
		log.Warn(err.Error())
		return err
	}
	return nil
}

// GetExchangeRule 从数据库中获取优惠卷生成规则
func GetExchangeRule(exchangeID string) (string, error) {
	ruleJSON := ""
	sql := "SELECT rule FROM exchange_rule WHERE exchange_id=?"
	info, err := qingkeMysqlHelper.Query(sql, exchangeID)
	if err != nil {
		log.Warn(err.Error())
		return "", err
	}
	if len(info) <= 0 {
		return "", nil
	}
	row := info[0]
	utility.SetTypeValue(row["rule"], reflect.ValueOf(&ruleJSON).Elem())
	return ruleJSON, nil
}

// RecordReceiveExchange 记录优惠码领取情况
func RecordReceiveExchange(exchangeID string, uid string, cid int64, ccode string) error {
	sql := "INSERT INTO receive_exchange(ccode,exchange_id,receiver,cid) VALUES(?,?,?,?) "
	_, err := qingkeMysqlHelper.Exec(sql, ccode, exchangeID, uid, cid)
	if err != nil {
		log.Warn(err.Error())
		return err
	}
	return nil
}
